package src.Client;

import src.common.MessageType;
import src.common.impl.Message;

import java. awt.Color;
import java. awt.event. *;
import java.io.IOException;
import java.io.ObjectOutputStream;
import java.io.OutputStream;
import javax.swing .*;

public class FriendChat extends JFrame implements ActionListener{
    JTextArea jta;
    JScrollPane jsp;
    JTextField jtf;
    JButton jb;

    String sender;
    String receiver;
    public FriendChat (String sender, String receiver) {

        this.sender = sender;
        this.receiver = receiver;

        jta=new JTextArea();//多行文本框
        jta.setForeground (Color.red) ;
        jsp=new JScrollPane (jta) ;
        this.add (jsp, "Center") ;

        jtf=new JTextField(15);//单行文本框
        jb=new JButton("发送");
        jb.addActionListener (this) ;
        jb.setForeground (Color.blue) ;
        JPanel jp=new JPanel () ;
        jp.add(jtf);
        jp.add(jb);
        this.add (jp, "South") ;

        this.setSize(350,250);
        //this. setDefaultCloseOperation (EXIT_ON_CLOSE) ;
        this.setLocationRelativeTo (null) ;

        this.setTitle(sender+"--to--"+receiver+"的聊天界面");

        this.setIconImage (new ImageIcon ("src/images/duck2.gif").getImage());
        this.setVisible (true) ;

    }


    public void actionPerformed (ActionEvent e) {
        if(e.getSource() == jb){//点击发送按钮
            jta.append(jtf.getText()+"\r\n");//在多行文本框中追加新的文本
            Message message = new Message();
            message.setSender(sender);
            message.setReceiver(receiver);
            message.setContent(jtf.getText());
            message.setMessageType(MessageType.COMMON_CHAT_MESSAGE);
            try {
                OutputStream os = YYChatClientConnection.s.getOutputStream();
                ObjectOutputStream oos = new ObjectOutputStream(os);
                oos.writeObject(message);
            }catch (IOException ee){
                ee.printStackTrace();
            }
        }

    }

    public void append(Message message){
        jta.append(message.getSendTime()+"\r\n"+message.getSender()+"对你说: "+message.getContent()+"\r\n");
    }


}